<template>
	<view class="detail-container">
		<!-- 帖子内容 -->
		<view class="post-card" v-if="post">
			<view class="post-header">
				<view class="user-info">
					<view class="user-avatar" :style="{ backgroundColor: post.userColor }">
						{{ post.userNickname.substring(0, 1) }}
					</view>
					<view class="user-nickname">{{ post.userNickname }}</view>
					<view class="post-time">{{ formatTime(post.createTime) }}</view>
				</view>
				<view class="post-tag" :style="{ backgroundColor: getTagColor(post.tagId, 0.1), color: getTagColor(post.tagId) }">
					{{ getTagName(post.tagId) }}
				</view>
			</view>
			
			<view class="post-content">
				<view class="post-title">{{ post.title }}</view>
				<view class="post-text">{{ post.content }}</view>
				
				<!-- 图片展示 -->
				<view class="post-images" v-if="post.images && post.images.length > 0">
					<image 
						v-for="(img, imgIndex) in post.images" 
						:key="imgIndex" 
						:src="img" 
						mode="widthFix" 
						class="post-image"
						@tap="previewImage(post.images, imgIndex)"
					></image>
				</view>
			</view>
			
			<view class="post-footer">
				<view class="action-item" @tap="likePost">
					<text class="iconfont" :class="post.isLiked ? 'icon-like-filled' : 'icon-like'"></text>
					<text class="count">{{ post.likes }}</text>
				</view>
				<view class="action-item">
					<text class="iconfont icon-comment"></text>
					<text class="count">{{ post.comments.length }}</text>
				</view>
				<view class="action-item" @tap="sharePost">
					<text class="iconfont icon-share"></text>
					<text class="count">分享</text>
				</view>
			</view>
		</view>
		
		<!-- 评论列表 -->
		<view class="comment-section">
			<view class="section-title">
				<text>评论 ({{ post?.comments?.length || 0 }})</text>
			</view>
			
			<view class="comment-list" v-if="post && post.comments && post.comments.length > 0">
				<view class="comment-item" v-for="(comment, index) in post.comments" :key="comment.id">
					<view class="comment-user">
						<view class="user-avatar" :style="{ backgroundColor: comment.userColor }">
							{{ comment.userNickname.substring(0, 1) }}
						</view>
						<view class="user-info">
							<view class="user-nickname">{{ comment.userNickname }}</view>
							<view class="comment-time">{{ formatTime(comment.createTime) }}</view>
						</view>
					</view>
					
					<view class="comment-content">
						{{ comment.content }}
					</view>
					
					<view class="comment-actions">
						<view class="action-btn" @tap="likeComment(comment)">
							<text class="iconfont" :class="comment.isLiked ? 'icon-like-filled' : 'icon-like'"></text>
							<text class="count">{{ comment.likes }}</text>
						</view>
						<view class="action-btn" @tap="replyComment(comment)">
							<text class="iconfont icon-reply"></text>
							<text class="count">回复</text>
						</view>
					</view>
				</view>
			</view>
			
			<view class="empty-comment" v-else>
				<image src="/static/images/community/empty-comment.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">暂无评论，快来发表第一条评论吧</text>
			</view>
		</view>
		
		<!-- 评论输入框 -->
		<view class="comment-input-area">
			<input 
				class="comment-input"
				type="text"
				v-model="commentText"
				placeholder="写下你的评论..."
				:focus="inputFocus"
				@blur="inputFocus = false"
			/>
			<button class="send-btn" :disabled="!commentText.trim()" @tap="submitComment">发送</button>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue'
	import { getPostDetail, likePost as likePostApi, createComment } from '@/common/api/community.js'
	
	// 确保__route__存在
	if (typeof __route__ === 'undefined') {
		try {
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			// @ts-ignore
			global.__route__ = currentPage.route;
		} catch (e) {
			console.error('获取当前页面路径失败:', e);
			// @ts-ignore
			global.__route__ = '/pages/community/detail';
		}
	}
	
	// 标签列表
	const tags = [
		{ id: 0, name: '全部', color: '#8cc9a1' },
		{ id: 1, name: '求助', color: '#f0ad4e' },
		{ id: 2, name: '分享', color: '#5bc0de' },
		{ id: 3, name: '讨论', color: '#d9534f' },
		{ id: 4, name: '经验', color: '#9370db' },
		{ id: 5, name: '饮食', color: '#28a745' },
		{ id: 6, name: '运动', color: '#fd7e14' },
		{ id: 7, name: '科普', color: '#17a2b8' }
	]
	
	// 帖子数据
	const post = ref(null)
	
	// 评论文本
	const commentText = ref('')
	
	// 输入框焦点
	const inputFocus = ref(false)
	
	// 当前回复的评论
	const replyTo = ref(null)
	
	// 获取标签名称
	const getTagName = (tagId) => {
		const tag = tags.find(t => t.id === tagId)
		return tag ? tag.name : '未知'
	}
	
	// 获取标签颜色
	const getTagColor = (tagId, alpha = 1) => {
		const tag = tags.find(t => t.id === tagId)
		if (!tag) return '#8cc9a1'
		
		if (alpha === 1) {
			return tag.color
		} else {
			// 将颜色转换为rgba格式
			const color = tag.color
			if (color.startsWith('#')) {
				const r = parseInt(color.slice(1, 3), 16)
				const g = parseInt(color.slice(3, 5), 16)
				const b = parseInt(color.slice(5, 7), 16)
				return `rgba(${r}, ${g}, ${b}, ${alpha})`
			}
			return color
		}
	}
	
	// 格式化时间
	const formatTime = (timestamp) => {
		const date = new Date(timestamp)
		const now = new Date()
		const diff = now - date
		
		// 小于1分钟
		if (diff < 60 * 1000) {
			return '刚刚'
		}
		// 小于1小时
		if (diff < 60 * 60 * 1000) {
			return `${Math.floor(diff / (60 * 1000))}分钟前`
		}
		// 小于24小时
		if (diff < 24 * 60 * 60 * 1000) {
			return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
		}
		// 小于30天
		if (diff < 30 * 24 * 60 * 60 * 1000) {
			return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
		}
		
		// 超过30天显示具体日期
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
	}
	
	// 点赞帖子
	const likePost = async () => {
		if (!post.value) return
		
		try {
			// 更新本地状态
			const isLike = !post.value.isLiked
			post.value.isLiked = isLike
			post.value.likes = isLike ? post.value.likes + 1 : Math.max(0, post.value.likes - 1)
			
			// 调用API更新点赞状态
			const res = await likePostApi(post.value.id, isLike)
			
			if (res.code !== 0) {
				throw new Error(res.message || '操作失败')
			}
		} catch (e) {
			console.error('点赞失败:', e)
			// 恢复原状态
			post.value.isLiked = !post.value.isLiked
			post.value.likes = post.value.isLiked ? post.value.likes + 1 : Math.max(0, post.value.likes - 1)
			
			uni.showToast({
				title: '操作失败，请重试',
				icon: 'none'
			})
		}
	}
	
	// 点赞评论
	const likeComment = async (comment) => {
		try {
			// 更新本地状态
			const isLike = !comment.isLiked
			comment.isLiked = isLike
			comment.likes = isLike ? comment.likes + 1 : Math.max(0, comment.likes - 1)
			
			// 这里应该调用API更新点赞状态
			// 但在Mock环境中，我们只更新本地存储
			const comments = uni.getStorageSync('communityComments') || []
			const index = comments.findIndex(item => item.id === comment.id)
			
			if (index !== -1) {
				comments[index].isLiked = isLike
				comments[index].likes = comment.likes
				uni.setStorageSync('communityComments', comments)
			}
			
			uni.showToast({
				title: isLike ? '点赞成功' : '已取消点赞',
				icon: 'none'
			})
		} catch (e) {
			console.error('点赞评论失败:', e)
			// 恢复原状态
			comment.isLiked = !comment.isLiked
			comment.likes = comment.isLiked ? comment.likes + 1 : Math.max(0, comment.likes - 1)
			
			uni.showToast({
				title: '操作失败，请重试',
				icon: 'none'
			})
		}
	}
	
	// 回复评论
	const replyComment = (comment) => {
		replyTo.value = comment
		commentText.value = `回复 ${comment.userNickname}：`
		inputFocus.value = true
	}
	
	// 分享帖子
	const sharePost = () => {
		uni.showActionSheet({
			itemList: ['分享到微信', '复制链接'],
			success: (res) => {
				if (res.tapIndex === 0) {
					uni.showToast({
						title: '分享功能将在后续完善',
						icon: 'none'
					})
				} else if (res.tapIndex === 1) {
					uni.setClipboardData({
						data: `https://xuetang.app/community/detail?id=${post.value.id}`,
						success: () => {
							uni.showToast({
								title: '链接已复制',
								icon: 'success'
							})
						}
					})
				}
			}
		})
	}
	
	// 预览图片
	const previewImage = (images, current) => {
		uni.previewImage({
			urls: images,
			current: images[current]
		})
	}
	
	// 提交评论
	const submitComment = async () => {
		if (!commentText.value.trim()) return
		
		uni.showLoading({
			title: '发送中...'
		})
		
		try {
			const commentData = {
				content: commentText.value,
				replyTo: replyTo.value ? replyTo.value.id : null
			}
			
			// 调用API发表评论
			const res = await createComment(post.value.id, commentData)
			
			if (res.code === 0) {
				// 添加到评论列表
				post.value.comments.unshift(res.data)
				
				// 清空输入
				commentText.value = ''
				replyTo.value = null
				
				uni.showToast({
					title: '评论成功',
					icon: 'success'
				})
			} else {
				throw new Error(res.message || '评论失败')
			}
		} catch (e) {
			console.error('评论失败:', e)
			uni.showToast({
				title: typeof e === 'string' ? e : '评论失败，请重试',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}
	
	// 获取帖子详情
	const loadPostDetail = async () => {
		uni.showLoading({
			title: '加载中...'
		})
		
		try {
			// 获取页面参数
			const pages = getCurrentPages()
			const currentPage = pages[pages.length - 1]
			const id = currentPage.$page?.options?.id || currentPage.options?.id
			
			if (!id) {
				throw new Error('帖子ID不存在')
			}
			
			// 调用API获取帖子详情
			const res = await getPostDetail(id)
			
			if (res.code === 0) {
				post.value = res.data
			} else {
				throw new Error(res.message || '获取帖子失败')
			}
		} catch (e) {
			console.error('获取帖子详情失败:', e)
			uni.showToast({
				title: typeof e === 'string' ? e : '获取帖子失败',
				icon: 'none'
			})
			
			// 失败后返回上一页
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		} finally {
			uni.hideLoading()
		}
	}
	
	// 页面加载时获取帖子详情
	onMounted(() => {
		loadPostDetail()
	})
</script>

<style lang="scss">
	.detail-container {
		min-height: 100vh;
		background-color: #f5f7fa;
		padding-bottom: 120rpx; // 留出评论输入框的空间
		
		.post-card {
			background-color: #fff;
			padding: 30rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
			
			.post-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				
				.user-info {
					display: flex;
					align-items: center;
					
					.user-avatar {
						width: 80rpx;
						height: 80rpx;
						border-radius: 50%;
						background-color: #8cc9a1;
						color: #fff;
						font-size: 32rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-right: 15rpx;
					}
					
					.user-nickname {
						font-size: 30rpx;
						color: #333;
						font-weight: 500;
						margin-right: 15rpx;
					}
					
					.post-time {
						font-size: 24rpx;
						color: #999;
					}
				}
				
				.post-tag {
					font-size: 24rpx;
					padding: 6rpx 20rpx;
					border-radius: 4rpx;
				}
			}
			
			.post-content {
				margin-bottom: 30rpx;
				
				.post-title {
					font-size: 36rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 20rpx;
				}
				
				.post-text {
					font-size: 30rpx;
					color: #333;
					line-height: 1.6;
					margin-bottom: 20rpx;
				}
				
				.post-images {
					display: flex;
					flex-direction: column;
					
					.post-image {
						width: 100%;
						margin-bottom: 20rpx;
						border-radius: 8rpx;
					}
				}
			}
			
			.post-footer {
				display: flex;
				border-top: 1px solid #f0f0f0;
				padding-top: 20rpx;
				
				.action-item {
					margin-right: 60rpx;
					display: flex;
					align-items: center;
					font-size: 28rpx;
					color: #666;
					
					.icon-like-filled {
						color: #f56c6c;
					}
					
					.count {
						margin-left: 8rpx;
					}
				}
			}
		}
		
		.comment-section {
			background-color: #fff;
			padding: 30rpx;
			margin-bottom: 20rpx;
			
			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 20rpx;
				border-bottom: 1px solid #f0f0f0;
				padding-bottom: 15rpx;
			}
			
			.comment-list {
				.comment-item {
					padding: 20rpx 0;
					border-bottom: 1px solid #f5f5f5;
					
					&:last-child {
						border-bottom: none;
					}
					
					.comment-user {
						display: flex;
						align-items: center;
						margin-bottom: 15rpx;
						
						.user-avatar {
							width: 60rpx;
							height: 60rpx;
							border-radius: 50%;
							color: #fff;
							font-size: 24rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							margin-right: 15rpx;
						}
						
						.user-info {
							.user-nickname {
								font-size: 28rpx;
								color: #333;
								margin-bottom: 5rpx;
							}
							
							.comment-time {
								font-size: 24rpx;
								color: #999;
							}
						}
					}
					
					.comment-content {
						font-size: 28rpx;
						color: #333;
						line-height: 1.5;
						margin-bottom: 15rpx;
						padding-left: 75rpx;
					}
					
					.comment-actions {
						display: flex;
						padding-left: 75rpx;
						
						.action-btn {
							margin-right: 30rpx;
							font-size: 24rpx;
							color: #999;
							display: flex;
							align-items: center;
							
							.icon-like-filled {
								color: #f56c6c;
							}
							
							.count {
								margin-left: 5rpx;
							}
						}
					}
				}
			}
			
			.empty-comment {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 60rpx 0;
				
				.empty-image {
					width: 200rpx;
					height: 200rpx;
					margin-bottom: 20rpx;
				}
				
				.empty-text {
					font-size: 28rpx;
					color: #999;
				}
			}
		}
		
		.comment-input-area {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #fff;
			padding: 20rpx 30rpx;
			display: flex;
			align-items: center;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
			
			.comment-input {
				flex: 1;
				height: 80rpx;
				background-color: #f5f5f5;
				border-radius: 40rpx;
				padding: 0 30rpx;
				font-size: 28rpx;
			}
			
			.send-btn {
				width: 120rpx;
				height: 80rpx;
				line-height: 80rpx;
				background-color: #8cc9a1;
				color: #fff;
				font-size: 28rpx;
				border-radius: 40rpx;
				margin-left: 20rpx;
				padding: 0;
				
				&[disabled] {
					background-color: #cccccc;
					color: #ffffff;
				}
			}
		}
	}
</style> 